package util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import bean.FileInfo;

public class FileUtil {
	public static String getContent(FileInfo fi) {

		if (null == fi.getContent() || fi.getContent().equals("")) {
			// TODO: File name need to be modified.
			return readFile(fi.getDirectory() + fi.getName());
		} else {
			return fi.getContent();
		}
	}

	public static boolean writeFileInfo(FileInfo fi) throws Exception {
		if (null == fi.getContent() || fi.getContent().equals("")) {
			throw new Exception("Null content, can not write file!");
		} else {
			return writeFile(fi.getDirectory() + fi.getName() + "."
					+ fi.getType().toLowerCase(), fi.getContent());
		}
	}
	
	public static boolean writeFile(String fileName, String fileContent) {
		try {
			File file = new File(fileName);
			BufferedWriter output = new BufferedWriter(new FileWriter(file));
			output.write(fileContent);
			output.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	public static String readFile(String fileName) {
		StringBuffer sb = new StringBuffer();
		String s = "";
		try {
			File file = new File(fileName);
			if (file.exists()) {
				System.out.println("File exists, use current file.");
			} else {
				throw new Exception("File not found!");
			}
			BufferedReader input = new BufferedReader(new FileReader(file));

			while ((s = input.readLine()) != null) {
				sb.append(s);
			}
			System.out.println("File content is: " + sb.toString());
			input.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
}
